package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.OBUUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.OBUUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.EmptyUtil;
import io.renren.modules.basedata.dao.OBUDao;
import io.renren.modules.basedata.entity.Tbl_OBU;
import io.renren.modules.basedata.service.OBUService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class OBUServiceImpl implements OBUService {
    private static final Logger log = LoggerFactory.getLogger(OBUServiceImpl.class);
    @Autowired
    private OBUDao obuDao;
    @Override
    public String obuUpload() throws Exception {
        log.info("开始获取未上传OBU信息");
        List<Tbl_OBU> list = getOBUList();//获取未上传OBU信息
        Tbl_OBU obu=null;
        int operResult=0;

        String fileName ="";

        if(list!=null&&list.size()>0){

            for(int i=0;i<list.size();i++){
                obu = list.get(i);
                OBUUploadRequest localOBUUploadRequest = new OBUUploadRequest();
                localOBUUploadRequest.setId(obu.getId().trim());
                localOBUUploadRequest.setBrand(obu.getBrand());
                try {
                    localOBUUploadRequest.setModel(obu.getModel().trim());
                } catch (Exception e) {
                    localOBUUploadRequest.setModel("0");
                    log.info("上传OBU'"+obu.getId()+"'填充'OBU型号Model'失败，填充默认值'0'："+e.getMessage());
                }
                localOBUUploadRequest.setUserId(obu.getUserId().trim());
                localOBUUploadRequest.setVehicleId(obu.getVehicleId().trim());
                localOBUUploadRequest.setEnableTime(DateUtil.formatDateTimes(obu.getEnableTime()));
//				localOBUUploadRequest.setExpireTime(DateUtil.formatDate(obu.getExpireTime()));
                if(obu.getExpireTime().before(obu.getEnableTime())){
                    localOBUUploadRequest.setExpireTime(DateUtil.formatDate(new Date()));
                }else{
                    try {
                        localOBUUploadRequest.setExpireTime(DateUtil.formatDate(obu.getExpireTime()));////必填
                    } catch (Exception e) {
                        localOBUUploadRequest.setExpireTime(DateUtil.formatDate(new Date()));
                        log.info("上传OBU'"+obu.getId()+"'填充'OBU到期时间ExpireTime'失败，填充默认值'new Date()':"+e.getMessage());
                    }
                }
                localOBUUploadRequest.setRegisteredType(obu.getRegisteredType());
                localOBUUploadRequest.setRegisteredChannelId(obu.getRegisteredChannelId().trim());
                localOBUUploadRequest.setRegisteredTime(DateUtil.formatDateTimes(obu.getRegisteredTime()));
                localOBUUploadRequest.setInstallType(obu.getInstallType());
                if(EmptyUtil.isNotEmpty(obu.getInstallChannelId())){
                    try {
                        localOBUUploadRequest.setInstallChannelId(obu.getInstallChannelId().trim());//非必填
                    } catch (Exception e) {
                        log.info("上传OBU'"+obu.getId()+"'填充'OBU安装/激活地点InstallChannelId'失败:"+e.getMessage());
                    }
                }
                localOBUUploadRequest.setInstallTime(DateUtil.formatDateTimes(obu.getInstallTime()));
                localOBUUploadRequest.setStatus(obu.getStatus());
                localOBUUploadRequest.setStatusChangeTime(DateUtil.formatDateTimes(obu.getStatusChangeTime()));
                localOBUUploadRequest.setOperation(obu.getFlag());
                //获取发送文件名
                fileName = ETCCommHelper.getFileName(localOBUUploadRequest,"65");
                //生成就json文件
//				CreateFileUtil.createJsonFile(localOBUUploadRequest.toJsonStr(), "",fileName);

                try{
                    //指定响应的协议模型,调用upload发送数据
                    OBUUploadResponse response = ETCCommHelper.sdtsUpload(fileName, localOBUUploadRequest, OBUUploadResponse.class);

                    log.info("上传OBU信息成功,服务器返回："+response.toJson());

                    if(response!=null&&response.getInfo().equals("成功！")){

                        //上传成功,更新客户卡信息表状态
                        if(localOBUUploadRequest.getOperation()!=3){//不是删除操作,只变更数据状态

                            if(obuDao.updateUploadOBUflag(obu.getId())==1){

                                log.info("更新OBU信息数据成功");

                                operResult++;

                            }else{

                                log.info("更新OBU信息数据失败");
                            }

                        }else{//删除操作,删除该数据

                            if(obuDao.deleteUploadOBUflag(obu.getId())==1){

                                log.info("删除OBU信息数据成功");

                                operResult++;

                            }else{

                                log.info("删除OBU信息数据失败");

                            }

                        }

                    }else{
                        log.info("上传OBU信息失败,失败信息："+response.getInfo());

                        obuDao.updateUploadOBUflagError(obu.getId());
                    }
                }catch(IOException e){

                    log.error("上传OBU信息失败,失败信息：", e);

                    continue;

                }catch (ApiRequestException apie) {

                    log.error("上传OBU信息失败,失败信息：", apie);

                    if(apie.getErrCode()==707){
                        obuDao.updateUploadOBUflag(obu.getId());
                    }else if(apie.getErrCode()==703||apie.getErrCode()==704){
                        obuDao.updateUploadOBUflagError(obu.getId());
                    }

                    continue;
                }
            }
            log.info("上传成功："+operResult+"条数据");
            return "OBU信息上传结束!";
        }
        return "无OBU信息,上传结束...";

    }
    //获取充值信息
    @SuppressWarnings("unchecked")
    public List<Tbl_OBU> getOBUList() throws Exception {
        List<Tbl_OBU> list;
        try {
            list = obuDao.getUnuploadOBUList();
        } catch (Exception e1) {
            e1.printStackTrace();
            log.error("获取未上传OBU信息失败!错误信息：", e1);
            throw new Exception("获取未上传OBU信息失败："+e1.getMessage());
        }
        return list;
    }
}
